{% extends "tools/base_tool.html" %}

{% block extra_head %}
<!-- 引入Markdown解析库 -->
<script src="/node_modules/marked/marked.min.js"></script>
<!-- 引入代码高亮库 -->
<!-- <script src="/node_modules/highlight.js/lib/index.js"></script> -->
<script src="/static/js/highlight.min.js"></script>
<!-- 引入Feather图标库 -->
<script src="/node_modules/feather-icons/dist/feather.min.js"></script>
<!-- 引入通用样式和Markdown编辑器样式 -->
<link rel="stylesheet" href="/static/css/common.css">
<link rel="stylesheet" href="/static/css/markdown-editor.css">
{% endblock %}

{% block content %}
<div class="container py-4">
  <div class="row mb-4">
    <div class="col-12">
      <div class="card">
        <div class="card-header bg-primary text-white d-flex justify-content-between align-items-center">
          <h5 class="mb-0">在线 MarkDown 编辑器</h5>
          <div>
            <button id="btn-save" class="btn btn-sm btn-light"><i data-feather="save" class="me-1"></i>保存</button>
            <button id="btn-clear" class="btn btn-sm btn-light ms-2"><i data-feather="trash-2" class="me-1"></i>清空</button>
          </div>
        </div>
        <div class="card-body">
          <p class="card-text">
            Markdown 是一种轻量级标记语言，它允许人们使用易读易写的纯文本格式编写文档，然后转换成有效的HTML文档。
          </p>
          
          <div class="toolbar">
            <div class="toolbar-group">
              <button class="btn btn-sm btn-outline-primary" data-action="heading" data-param="1"><i data-feather="type" class="me-1"></i>H1</button>
              <button class="btn btn-sm btn-outline-primary" data-action="heading" data-param="2"><i data-feather="type" class="me-1"></i>H2</button>
              <button class="btn btn-sm btn-outline-primary" data-action="heading" data-param="3"><i data-feather="type" class="me-1"></i>H3</button>
            </div>
            
            <div class="toolbar-group">
              <button class="btn btn-sm btn-outline-primary" data-action="bold"><i data-feather="bold" class="me-1"></i>粗体</button>
              <button class="btn btn-sm btn-outline-primary" data-action="italic"><i data-feather="italic" class="me-1"></i>斜体</button>
              <button class="btn btn-sm btn-outline-primary" data-action="strikethrough"><i data-feather="delete" class="me-1"></i>删除线</button>
            </div>
            
            <div class="toolbar-group">
              <button class="btn btn-sm btn-outline-primary" data-action="list-ul"><i data-feather="list" class="me-1"></i>无序列表</button>
              <button class="btn btn-sm btn-outline-primary" data-action="list-ol"><i data-feather="list-ordered" class="me-1"></i>有序列表</button>
              <button class="btn btn-sm btn-outline-primary" data-action="blockquote"><i data-feather="message-square" class="me-1"></i>引用</button>
            </div>
            
            <div class="toolbar-group">
              <button class="btn btn-sm btn-outline-primary" data-action="link"><i data-feather="link" class="me-1"></i>链接</button>
              <button class="btn btn-sm btn-outline-primary" data-action="image"><i data-feather="image" class="me-1"></i>图片</button>
              <button class="btn btn-sm btn-outline-primary" data-action="code"><i data-feather="code" class="me-1"></i>代码</button>
              <button class="btn btn-sm btn-outline-primary" data-action="table"><i data-feather="grid" class="me-1"></i>表格</button>
            </div>
          </div>
          
          <div class="editor-container">
            <div class="editor-panel">
              <textarea id="markdown-editor" placeholder="在此输入Markdown内容..."></textarea>
            </div>
            <div class="preview-panel">
              <div id="markdown-preview"></div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  
  <div class="row">
    <div class="col-12">
      <div class="card">
        <div class="card-header bg-primary text-white">
          <h5 class="mb-0">Markdown 效果及格式示例</h5>
        </div>
        <div class="card-body">
          <div class="table-responsive">
            <table class="table table-bordered">
              <thead>
                <tr>
                  <th>Markdown语法</th>
                  <th>效果</th>
                </tr>
              </thead>
              <tbody>
                <tr>
                  <td><code># 标题1</code></td>
                  <td><h1 class="no-margin">标题1</h1></td>
                </tr>
                <tr>
                  <td><code>## 标题2</code></td>
                  <td><h2 class="no-margin">标题2</h2></td>
                </tr>
                <tr>
                  <td><code>**粗体文本**</code></td>
                  <td><strong>粗体文本</strong></td>
                </tr>
                <tr>
                  <td><code>*斜体文本*</code></td>
                  <td><em>斜体文本</em></td>
                </tr>
                <tr>
                  <td><code>~~删除线~~</code></td>
                  <td><del>删除线</del></td>
                </tr>
                <tr>
                  <td><code>[链接文本](https://example.com)</code></td>
                  <td><a href="#">链接文本</a></td>
                </tr>
                <tr>
                  <td><code>![图片描述](图片URL)</code></td>
                  <td>显示图片</td>
                </tr>
                <tr>
                  <td><code>- 无序列表项</code></td>
                  <td><ul class="no-margin"><li>无序列表项</li></ul></td>
                </tr>
                <tr>
                  <td><code>1. 有序列表项</code></td>
                  <td><ol class="no-margin"><li>有序列表项</li></ol></td>
                </tr>
                <tr>
                  <td><code>```<br>代码块<br>```</code></td>
                  <td><pre class="no-margin"><code>代码块</code></pre></td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
{% endblock %}

{% block scripts %}
<script>
  document.addEventListener('DOMContentLoaded', function() {
    const editor = document.getElementById('markdown-editor');
    const preview = document.getElementById('markdown-preview');
    const saveBtn = document.getElementById('btn-save');
    const clearBtn = document.getElementById('btn-clear');
    
    // 初始化highlight.js
    hljs.highlightAll();
    
    // 配置marked选项
    marked.setOptions({
      highlight: function(code, lang) {
        try {
          if (lang && hljs && hljs.getLanguage(lang)) {
            return hljs.highlight(code, { language: lang }).value;
          } else if (hljs) {
            return hljs.highlightAuto(code).value;
          }
          return code; // 如果hljs未加载，返回原始代码
        } catch (error) {
          console.error('代码高亮错误:', error);
          return code;
        }
      },
      breaks: true
    });
    
    // 初始化编辑器内容
    const savedContent = localStorage.getItem('markdown-content');
    if (savedContent) {
      editor.value = savedContent;
      updatePreview();
    } else {
      // 默认示例内容
      editor.value = `# 在线 MarkDown 编辑器

这是一个简单的Markdown编辑器示例。

## 功能特点

- 实时预览
- 语法高亮
- 本地存储
- 常用Markdown格式工具栏

## 代码示例

\`\`\`javascript
function hello() {
  console.log("Hello, Markdown!");
}
\`\`\`

## 表格示例

| 名称 | 描述 |
| ---- | ---- |
| Markdown | 轻量级标记语言 |
| HTML | 超文本标记语言 |

> 这是一个引用示例。Markdown是一种轻量级标记语言，创始人为约翰·格鲁伯（John Gruber）。
`;
      updatePreview();
    }
    
    // 实时更新预览
    editor.addEventListener('input', updatePreview);
    
    function updatePreview() {
      const markdownText = editor.value;
      try {
        // 确保marked库已正确加载
        if (typeof marked !== 'undefined') {
          const htmlContent = marked.parse(markdownText);
          preview.innerHTML = htmlContent;
        } else {
          console.error('marked库未正确加载');
          preview.innerHTML = '<div class="alert alert-danger">Markdown解析库未正确加载</div>';
        }
      } catch (error) {
        console.error('Markdown解析错误:', error);
        preview.innerHTML = '<div class="alert alert-danger">Markdown解析错误</div>';
      }
      // 保存到本地存储
      localStorage.setItem('markdown-content', markdownText);
    }
    
    // 保存按钮
    saveBtn.addEventListener('click', function() {
      const markdownText = editor.value;
      const blob = new Blob([markdownText], { type: 'text/markdown' });
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = 'document.md';
      a.click();
      URL.revokeObjectURL(url);
    });
    
    // 清空按钮
    clearBtn.addEventListener('click', function() {
      if (confirm('确定要清空编辑器内容吗？')) {
        editor.value = '';
        updatePreview();
      }
    });
    
    // 工具栏功能
    const toolbarButtons = document.querySelectorAll('.toolbar button[data-action]');
    toolbarButtons.forEach(button => {
      button.addEventListener('click', function() {
        const action = this.getAttribute('data-action');
        const param = this.getAttribute('data-param');
        insertMarkdown(action, param);
      });
    });
    
    function insertMarkdown(action, param) {
      const start = editor.selectionStart;
      const end = editor.selectionEnd;
      const selectedText = editor.value.substring(start, end);
      let insertText = '';
      
      switch(action) {
        case 'heading':
          const hLevel = '#'.repeat(parseInt(param));
          insertText = `${hLevel} ${selectedText || '标题'}`;
          break;
        case 'bold':
          insertText = `**${selectedText || '粗体文本'}**`;
          break;
        case 'italic':
          insertText = `*${selectedText || '斜体文本'}*`;
          break;
        case 'strikethrough':
          insertText = `~~${selectedText || '删除线文本'}~~`;
          break;
        case 'list-ul':
          insertText = selectedText ? selectedText.split('\n').map(line => `- ${line}`).join('\n') : '- 列表项\n- 列表项\n- 列表项';
          break;
        case 'list-ol':
          if (selectedText) {
            insertText = selectedText.split('\n').map((line, i) => `${i+1}. ${line}`).join('\n');
          } else {
            insertText = '1. 列表项\n2. 列表项\n3. 列表项';
          }
          break;
        case 'blockquote':
          insertText = selectedText ? selectedText.split('\n').map(line => `> ${line}`).join('\n') : '> 引用文本';
          break;
        case 'link':
          insertText = `[${selectedText || '链接文本'}](https://example.com)`;
          break;
        case 'image':
          insertText = `![${selectedText || '图片描述'}](https://example.com/image.jpg)`;
          break;
        case 'code':
          if (selectedText.includes('\n')) {
            insertText = `\`\`\`\n${selectedText}\n\`\`\``;
          } else {
            insertText = `\`${selectedText || '代码'}\``;
          }
          break;
        case 'table':
          insertText = `| 标题1 | 标题2 | 标题3 |\n| ----- | ----- | ----- |\n| 内容1 | 内容2 | 内容3 |\n| 内容4 | 内容5 | 内容6 |`;
          break;
      }
      
      editor.focus();
      // 使用更可靠的方法替换选中文本
      const newValue = editor.value.substring(0, start) + insertText + editor.value.substring(end);
      editor.value = newValue;
      // 设置新的光标位置
      editor.selectionStart = start + insertText.length;
      editor.selectionEnd = start + insertText.length;
      updatePreview();
    }
    
    // 初始化图标
    document.addEventListener('DOMContentLoaded', function() {
      feather.replace();
    });
  });
</script>
{% endblock %}